package cn.schoolwow.quickdao.test.module.business.user.log.flow;

import cn.schoolwow.quickdao.domain.DAO;
import cn.schoolwow.quickdao.domain.database.parent.UpgradeRequest;
import cn.schoolwow.quickdao.domain.entity.Property;
import cn.schoolwow.quickdao.test.entity.Role;
import cn.schoolwow.quickdao.test.entity.User;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;

import java.util.ArrayList;
import java.util.List;

public class DatabaseUpgradeProcessFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        modifyMobileColumn(flowContext);
        modifyRoleStatus(flowContext);
    }

    @Override
    public String name() {
        return "数据库升级";
    }

    private void modifyMobileColumn(FlowContext flowContext){
        DAO dao = flowContext.checkInstanceData(DAO.class);
        List<UpgradeRequest> upgradeRequestList = (List<UpgradeRequest>) flowContext.getData("upgradeRequestList", new ArrayList<>());

        UpgradeRequest upgradeRequest = new UpgradeRequest();
        upgradeRequest.comment = "修改手机号字段类型";
        upgradeRequest.upgradeConsumer = d->{
            Property property = d.getProperty(User.class, "mobile");
            property.columnType = "varchar";
            property.range = "32";
            d.alterColumn(property.entity.tableName, property);
        };
        dao.upgrade(upgradeRequest.comment, upgradeRequest.upgradeConsumer);

        upgradeRequestList.add(upgradeRequest);
    }

    private void modifyRoleStatus(FlowContext flowContext){
        DAO dao = flowContext.checkInstanceData(DAO.class);
        List<UpgradeRequest> upgradeRequestList = (List<UpgradeRequest>) flowContext.getData("upgradeRequestList", new ArrayList<>());

        UpgradeRequest upgradeRequest = new UpgradeRequest();
        upgradeRequest.comment = "修改角色状态";
        upgradeRequest.upgradeConsumer = d->{
            d.query(Role.class)
                    .addUpdate("status", 1)
                    .execute()
                    .update();
        };
        dao.upgrade(upgradeRequest.comment, upgradeRequest.upgradeConsumer);

        upgradeRequestList.add(upgradeRequest);
    }
}
